import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config} from '../../../shared/smartadmin.config';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
declare var $: any;
declare var BMap: any;
declare var toMapPoint: any;
@Component({
  selector: 'sa-rail-loadBind',
  templateUrl: './rail-loadBind.component.html',
})
export class RailLoadBindComponent implements OnInit {
	tableData:any = []; //table数据
	totalCount:number = 0; //分页总条数
	selectedRow:boolean = false;//是否选择row数据状态 
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	selectedCarNumber:string='';
	selectedCompanyId:string = '';
	selectedCompanyName:string = '';
	companyId:string = '';
	mapMarkerData:string = '';//围栏选中id
	mapMarkerCar:string ='';//选中的车牌
	railName="";
	baiduMap:any;//百度地图
	railPath:any;//查看的地图围栏
	selectRowData:any;
	carBindList:any = [];//围栏车辆绑定详细列表
	carUseList = carTypeListObj.carUseList
	carDeatailUseList = carTypeListObj.carDeatailUseList
	
	constructor(private jsonApiService: JsonApiService,private router: Router,private activatedRoute: ActivatedRoute,) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage?queryParams.nowPage:1;
		});
	}
	//刷新
	refresh(){
		this.load();
	}
	ngOnInit() {
		this.load();
		this.initBaiduMap();
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/jstree/jstree.min.js').then(()=>{
				this.initCompanyList();//初始化公司树
				var tree_box = document.getElementById('tree_box');
				var company = document.getElementById('company');
				//公司树弹窗显示隐藏交互事件
				document.onclick=function(e:any){
					if(!(e.target === company||e.target.className === 'jstree-children'||e.target.className === 's_del_icon'||e.target.className === 'jstree-node  jstree-leaf'||e.target.className === 'jstree-icon jstree-ocl'||e.target.className ==='vision_tree'||e.target.className === 'jstree-node jstree-leaf jstree-closed')){ 
				        tree_box.className = tree_box.className.replace("tree_open","");
				   	} 
				}
			})
		})
	}
	//查看围栏,展开地图弹框
	mapModalOpen(row,val){
		this.selectRowData=row;
		this.drawMapRail(row);
		val.show();
	}
	bindCars(row){
		this.router.navigate(['/data-statistics/rail/rail-loadBind/rail-bindCar-page'],
		{ queryParams: {nowPage:this.curPage,pageType:'loadBind',markerId:row.id}});
	}
	addRail(){
		this.router.navigate(['/car/car-path'],{ queryParams: {nowPage:this.curPage}});
	}
	deleteRow(id){
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
			var reqdata = "id=" + id;
			this.jsonApiService.http('mapmarker/deletemarker.html', reqdata).subscribe(result => {
				this.jsonApiService.message(result.message);
				this.refresh();
			})
		})
	}
	initBaiduMap(){
		let map = new BMap.Map('baiduMap',{enableMapClick: false}); //创建地图实例
		this.baiduMap=map;
		map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
		var myCity = new BMap.LocalCity();
		myCity.get(function (result){
			let point=result.center;
		  	let city = new BMap.Point(point.lng, point.lat); //创建点坐标
		  	map.centerAndZoom(city, 12); //初始化地图，设置中心点坐标和地图级别
		});
	}
	//画地图围栏
	drawMapRail(rowData) {
		var obj=toMapPoint(rowData);
		if(!obj){
			return;
		}
		if(this.railPath){
			this.baiduMap.removeOverlay(this.railPath);
		}
		var point = new BMap.Point(obj.lng, obj.lat);
		if(obj.lnglats == ''||obj.lnglats == null) {
			this.railPath = new BMap.Circle(point, obj.radius, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建圆
		} else {
			if(!obj.lnglats){
				return;
			}
			var poitnArr = [];
			var lnglatsArr = obj.lnglats.split(';');
			for(var j = 0; j < lnglatsArr.length; j++) {
				if(lnglatsArr[j] !== "") {
					var arr = lnglatsArr[j].split(',');
					poitnArr.push(new BMap.Point(arr[0], arr[1]))
				}
			}
			this.railPath = new BMap.Polygon(poitnArr, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建多边形
		}
		this.baiduMap.addOverlay(this.railPath);
		setTimeout(function(){
			this.baiduMap.centerAndZoom(point,13); 
		}.bind(this),500)
	}
	ngOnDestroy(){
		document.onclick = null;
	}
	//擦除公司所选值
	delText(){
		this.selectedCompanyName = '';
		this.selectedCompanyId = '';
		$('#company').val("");
		this.companySearch();
		if($('#tree_box')[0].className.indexOf('tree_open')>0){
			$('#company').focus();
		}
	}
	//打开公司树
	companyClick(){
		$('#tree_box').toggleClass('tree_open');
	}
	//公司树模糊搜索
	companySearch(){
		var value = $('#company').val();
		$("#tree").jstree(true).search(value);
		let searchResult = $('.jstree-search').length;
		if(searchResult < 1){
			return;
		}
		$('.jstree-search').each(function(index, obj) {
			if(index < 1) {//js树搜索定位到结果的第一个地方；
				var container = $('#vision_tree'),
				scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#vision_tree').height() * 0.3});
			}
		})
	}
	//初始化公司树数据
	initCompanyList(){
		var that = this;
	 	$('#tree').jstree({
			"core": {
				'data': function(obj, callback) {       
					var jsonstr = "[]";       
					var jsonarray = eval('(' + jsonstr + ')');
					var url = 'company/companytree.html';
					$.ajax({        
						type: "POST",
				        url: config.BaseURL + url,
				        dataType: "json",
						xhrFields: {
							withCredentials: true
						},
//				        async: false,
				        success: function(result) {
							jsonarray = result;  
							callback.call(this, jsonarray); 
						}         
					});      
			},
			"themes": {
				"responsive": true
			},
			"multiple": false,
			"animation": 200,
			"dblclick_toggle": true,
			"expand_selected_onload": true
		},
		"plugins": ["search"]
		}).bind("activate_node.jstree", function(e, obj) {
			var currentNode = obj.node; // 获取当前节点   
			that.selectedCompanyName = currentNode.text;
			that.selectedCompanyId = currentNode.id;
			$('#company').val(currentNode.text).change();
			that.companySearch();
		})
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {
			return state.text;
		}
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//清除select2 数据
	clearSelect2(obj) {
		obj.empty();
		obj.prepend("<option value=''>请选择</option>");
	}
	//公司id拉取车辆
	//查询
	table_search(){
		this.curPage=1;
		this.load();
	}
	getUseTypeNameL1(key){
		if(key){
			return this.carUseList[key];
		}else{
			return '';
		}
	}
	getUseTypeNameL2(key){
		if(key){
			return this.carDeatailUseList[key];
		}else{
			return '';
		}
	}
	//围栏绑定车辆的详细信息
	carBindDetail(data,val){
		val.show();
		this.carBindList = [];
		let temArr = data.bindCarList;
		if(!temArr)return;
		for(let item of temArr){
			item.useTypeL1 = this.getUseTypeNameL1(item.useTypeL1);
			item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);
		}
		this.carBindList = temArr;
		return this.carBindList;
	}
	//关闭弹窗
	closeCarBind(val){
		val.hide();
		this.refresh();
	}
	//加载list数据
	load(){
		var postData={
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				name:common.stringTrim(this.railName),//围栏名称
				companyId:this.selectedCompanyId,
				typeId:'1',
			}
		}
		let reqdata='gridPager='+JSON.stringify(postData);
		this.jsonApiService.http("mapmarker/listCarMapMarker.html", reqdata).subscribe(data => {
			if(data.isSuccess){
				for(let item of data.exhibitDatas){
					item.bindMapMarkTime = item.bindMapMarkTime?item.bindMapMarkTime:'';
					item.bindMapMarkUser = item.bindMapMarkUser?item.bindMapMarkUser:'';
					item.mapMarker = item.mapMarker?item.mapMarker:{name:''};
				}
				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;
			}
		})
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	mapModalClose(val){
		val.hide();
	}
}
